<?php

namespace catchAdmin\drug\controller;

use app\common\model\Drug as DrugModel;
use catcher\CatchResponse;
use catcher\base\CatchRequest;
use catcher\base\CatchController;
use catcher\exceptions\FailedException;

class Drug extends CatchController
{
    protected $drug;

    public function __construct(DrugModel $drug)
    {
        $this->drug = $drug;
    }

    /**
     * 列表
     * @time 2023年08月16日
     * @return \think\response\Json
     */
    public function index(): \think\response\Json
    {
        return CatchResponse::paginate($this->drug->getList());
    }

    /**
     * 新增
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function save(CatchRequest $request): \think\response\Json
    {
        $req = $request->post();

        //是否存在数据
        $is_existence = $this->drug->where('deleted_at', 0)->field('code')->order('code', 'desc')->find();

        //存在数据，在原code上+1
        if ($is_existence) {
            $req["code"] = $is_existence['code'] + 1;
        } else {
            $req["code"] = 1;
        }
        $req['deleted_at'] = 0;
        return CatchResponse::success($this->drug->addData($req));
    }

    /**
     * 更新
     * @param string $id 主键
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function update(string $id, CatchRequest $request): \think\response\Json
    {
        return CatchResponse::success($this->drug->saveData($id, $request->post()));
    }

    /**
     * 删除
     * @param string $id
     * @return \think\response\Json
     */
    public function delete(string $id): \think\response\Json
    {
        return CatchResponse::success($this->drug->destroy($id));
    }

    /**
     * 获取药品
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function getDrug(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        if (!isset($req['name']) || empty($req['name'])) {
            throw new FailedException('请输入药品关键字');
        }
        $list = $this->drug->whereLike('name', $req['name'])->field('code,name')->order('created_at', 'desc')->select();
        return CatchResponse::success($list);
    }
}